import pymysql

import config


# 作废############################
def singleton(cls, *args, **kwargs):
    instances = {}

    def _singleton():
        if cls not in instances:
            instances[cls] = cls(*args, **kwargs)
        return instances[cls]

    return _singleton


@singleton
class mySQL:
    host = config.options.get('db_url')
    user = config.options.get('db_user')
    password = config.options.get('db_pass')
    dbName = config.options.get('db_name')

    def connect(self):
        self.db = pymysql.connect(self.host, self.user, self.password, self.dbName)
        self.cursor = self.db.cursor()

    def close(self):
        self.cursor.close()
        self.db.close()

    def get_one(self, sql):
        res = None
        try:
            self.connect()
            self.cursor.execute(sql)
            res = self.cursor.fetchone()
            self.close()
        except:
            print("searching failed")
        return res
